package com.i2works.smartluolong.web.controller.user;

import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.*;
import com.i2works.smartluolong.utils.common.WebUtil;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.company.CompanyApplyDO;
import com.i2works.smartluolong.web.entity.company.CompanyChangeDO;
import com.i2works.smartluolong.web.entity.court.CourtLawsuitDO;
import com.i2works.smartluolong.web.entity.court.CourtLawsuitQuery;
import com.i2works.smartluolong.web.entity.disability.DisabilityApplyDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoQuery;
import com.i2works.smartluolong.web.entity.flow.FlowProcessDO;
import com.i2works.smartluolong.web.entity.merchant.MerchantApplyDO;
import com.i2works.smartluolong.web.entity.org.OrgDO;
import com.i2works.smartluolong.web.entity.org.OrgQuery;
import com.i2works.smartluolong.web.entity.suggestion.SuggestionDO;
import com.i2works.smartluolong.web.entity.suggestion.SuggestionQuery;
import com.i2works.smartluolong.web.service.company.ICompanyApplyService;
import com.i2works.smartluolong.web.service.company.ICompanyChangeService;
import com.i2works.smartluolong.web.service.court.ICourtLawsuitService;
import com.i2works.smartluolong.web.service.disability.IDisabilityApplyService;
import com.i2works.smartluolong.web.service.flow.IFlowInfoService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.i2works.smartluolong.web.service.fooddrug.IFooddrugApplyService;
import com.i2works.smartluolong.web.service.fooddrug.IFooddrugCancelService;
import com.i2works.smartluolong.web.service.fooddrug.IFooddrugChangeService;
import com.i2works.smartluolong.web.service.merchant.IMerchantApplyService;
import com.i2works.smartluolong.web.service.org.IOrgService;
import com.i2works.smartluolong.web.service.suggestion.ISuggestionService;
import com.i2works.smartluolong.web.utils.BaseModule;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.ReflectUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户业务控制层
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/22 15:25
 */
@Controller
@RequestMapping("/user")
public class UserServiceController extends BaseModule {


    private final IFlowInfoService flowInfoService;
    private final IFlowProcessService flowProcessService;
    private final ICompanyApplyService companyApplyService;
    private final ICompanyChangeService companyChangeService;
    private final IFooddrugApplyService fooddrugApplyService;
    private final IFooddrugCancelService fooddrugCancelService;
    private final IFooddrugChangeService fooddrugChangeService;
    private final IDisabilityApplyService disabilityApplyService;
    private final ISuggestionService suggestionService;
    private final IOrgService orgService;
    private final IMerchantApplyService merchantApplyService;
    private final ICourtLawsuitService lawsuitService;
    @Autowired
    public UserServiceController(IFlowInfoService flowInfoService, IFlowProcessService flowProcessService, ICompanyApplyService companyApplyService, ICompanyChangeService companyChangeService, IFooddrugApplyService fooddrugApplyService, IFooddrugCancelService fooddrugCancelService, IFooddrugChangeService fooddrugChangeService, IDisabilityApplyService disabilityApplyService,ISuggestionService suggestionService, IOrgService orgService, IMerchantApplyService merchantApplyService,ICourtLawsuitService lawsuitService) {
        this.flowInfoService = flowInfoService;
        this.flowProcessService = flowProcessService;
        this.companyApplyService = companyApplyService;
        this.companyChangeService = companyChangeService;
        this.fooddrugApplyService = fooddrugApplyService;
        this.fooddrugCancelService = fooddrugCancelService;
        this.fooddrugChangeService = fooddrugChangeService;
        this.disabilityApplyService = disabilityApplyService;
        this.suggestionService = suggestionService;
        this.orgService = orgService;
        this.merchantApplyService = merchantApplyService;
        this.lawsuitService=lawsuitService;
    }

    /**
     * 办件列表
     */
    @GetMapping("/transactList")
    @ResponseBody
    public Result transactList(@ModelAttribute CourtLawsuitQuery courtLawsuitQuery) {
        try {
            courtLawsuitQuery.setUserId(getUserId());
            if(StringUtils.isEmpty(courtLawsuitQuery.getPlaintiffCardNumber())){
                courtLawsuitQuery.setPlaintiffCardNumber(null);
            }
            Integer queryCount = lawsuitService.queryCount(courtLawsuitQuery);
            List<CourtLawsuitDO> resultList = Lists.newArrayList();
            if (queryCount != 0) {
                 resultList = lawsuitService.queryList(courtLawsuitQuery);
                if (CollectionUtil.isNotEmpty(resultList)) {
                    for (CourtLawsuitDO lawsuitDO : resultList) {
                        lawsuitDO.setItemStatusText(itemStatusText(lawsuitDO.getStage()));
                        lawsuitDO.setParticulars("详情");
                    }
                }

            }
            return R.success(resultList, queryCount);
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
    }



    /**
     * 投诉建议列表
     */
    @GetMapping("/suggestionList")
    @ResponseBody
    public Result suggestionList(@ModelAttribute SuggestionQuery query) {
        try {
            query.setUserId(getUserId());
            Integer queryCount = suggestionService.queryCount(query);
            List<SuggestionDO> resultList = Lists.newArrayList();
            if (queryCount != 0) {
                resultList = suggestionService.queryList(query);
            }
            resultList = transform(resultList);
            return R.success(resultList, queryCount);
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
    }


    /**
     * 作废
     */
    @PostMapping("/invalid/action")
    @ResponseBody
    public Result invalid(@ModelAttribute FlowInfoDO flowInfoDO) {
        try {
            FlowInfoQuery query = new FlowInfoQuery();
            query.setUserId(getUserId());
            query.setItemId(flowInfoDO.getItemId());
            query.setItemType(flowInfoDO.getItemType());
            Integer queryCount = flowInfoService.queryCount(query);
            if (queryCount > 0) {

                FlowItemTypeEnum typeEnum = WebUtil.getEnum(FlowItemTypeEnum.class, flowInfoDO.getItemType(), null);
                Integer statusKey = 0;
                String statusText = "";
                Enum statusEnum = null;
                if (null != typeEnum) {
                    switch (typeEnum) {
                        //工商
                        case COMPANY_APPLY:
                            CompanyApplyDO companyApplyDO = new CompanyApplyDO();
                            companyApplyDO.setId(flowInfoDO.getItemId());
                            companyApplyDO.setApplyStatus(CompanyStatusEnum.STATUS_8.getKey());
                            companyApplyService.update(companyApplyDO);
                            statusEnum = CompanyStatusEnum.STATUS_8;
                            break;
                        case COMPANY_CHANGE:
                            CompanyChangeDO companyChangeDO = new CompanyChangeDO();
                            companyChangeDO.setId(flowInfoDO.getItemId());
                            companyChangeDO.setChangeStatus(CompanyStatusEnum.STATUS_8.getKey());
                            companyChangeService.update(companyChangeDO);
                            statusEnum = CompanyStatusEnum.STATUS_8;
                            break;
                        case COMPANY_RECORD:
                            break;
                        //食药
                        case FOODDRUG_APPLY:
                            break;
                        case FOODDRUG_CHANGE:
                            break;
                        case FOODDRUG_CANCEL:
                            break;
                        //个体户
                        case MERCHANT_APPLY:
                            MerchantApplyDO merchantApplyDO = new MerchantApplyDO();
                            merchantApplyDO.setId(flowInfoDO.getItemId());
                            merchantApplyDO.setApplyStatus(MerchantStatusEnum.STATUS_5.getKey());
                            merchantApplyService.update(merchantApplyDO);
                            statusEnum = MerchantStatusEnum.STATUS_5;
                            break;
                        case MERCHANT_CHANGE:
                            break;
                        case MERCHANT_RECORD:
                            break;

                        //残疾证
                        case DISABILITY_APPLY:
                            statusEnum = executeInvalidDisability(flowInfoDO);
                            break;
                        case DISABILITY_CHANGE:
                            statusEnum =executeInvalidDisability(flowInfoDO);
                            break;
                        case DISABILITY_CANCEL:
                            statusEnum =executeInvalidDisability(flowInfoDO);
                            break;
                        case DISABILITY_REAPPLY:
                            statusEnum =executeInvalidDisability(flowInfoDO);
                            break;
                    }
                }

                //更新进度表
                Integer key = Integer.parseInt(String.valueOf(ReflectUtil.getFieldValue(statusEnum, "key")));
                String text = String.valueOf(ReflectUtil.getFieldValue(statusEnum, "text"));
                flowInfoDO.setItemStatus(key);
                flowInfoService.update(flowInfoDO);
                //记录
                FlowProcessDO flowProcessDO = new FlowProcessDO();
                flowProcessDO.setItemId(flowInfoDO.getItemId());
                flowProcessDO.setItemType(flowInfoDO.getItemType());
                flowProcessDO.setItemTitle(flowInfoDO.getItemName());
                flowProcessDO.setAuditStatus(key);
                flowProcessDO.setMessage("用户《" + getUserName() + "》提交" +text);
                flowProcessDO.setUpdateName(getUserName());
                flowProcessDO.setCreateName(getUserName());
                flowProcessService.save(flowProcessDO);
                return R.success();
            }
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            return R.error(MsgEnum.FIND_ERROR.getMsg());
        }
        return R.error(MsgEnum.EDIT_ERROR.getMsg());
    }


    /**
     * 执行作废残疾证
     */
    private Enum executeInvalidDisability(FlowInfoDO flowInfoDO) throws ServiceException {
        flowInfoDO.setItemStatus(DisabilityStatusEnum.STATUS_8.getKey());
        flowInfoService.update(flowInfoDO);
        DisabilityApplyDO applyDO = new DisabilityApplyDO();
        applyDO.setId(flowInfoDO.getItemId());
        applyDO.setApplyStatus(DisabilityStatusEnum.STATUS_8.getKey());
        disabilityApplyService.update(applyDO);
        return DisabilityStatusEnum.STATUS_8;
    }



    private List<SuggestionDO> transform(List<SuggestionDO> list) {
        List<SuggestionDO> newList = new ArrayList<SuggestionDO>();
        OrgQuery query = new OrgQuery();
        if (list.size() != 0) {
            for (SuggestionDO suggestionDO : list) {
                OrgDO org = new OrgDO();
                try {
                    query.setId(suggestionDO.getOrgId());
                    org = orgService.query(query);
                    suggestionDO.setOrgName(org.getOrgName());
                    newList.add(suggestionDO);
                } catch (ServiceException e) {
                    e.printStackTrace();
                }
            }
        }

        return newList;
    }

    /**
     * 获取项目状态字符串，并返回工作流信息实体
     */
    private FlowInfoDO getItemStatusText(FlowInfoDO flowInfoDO) {
        FlowItemTypeEnum[] values = FlowItemTypeEnum.values();
        List<String> companyList = Lists.newArrayList(FlowItemTypeEnum.COMPANY_APPLY.getKey(), FlowItemTypeEnum.COMPANY_CHANGE.getKey(), FlowItemTypeEnum.COMPANY_RECORD.getKey());
        List<String> merchantList = Lists.newArrayList(FlowItemTypeEnum.MERCHANT_APPLY.getKey(), FlowItemTypeEnum.MERCHANT_CHANGE.getKey(), FlowItemTypeEnum.MERCHANT_RECORD.getKey());
        List<String> fooddrugList = Lists.newArrayList(FlowItemTypeEnum.FOODDRUG_APPLY.getKey(), FlowItemTypeEnum.FOODDRUG_CHANGE.getKey(), FlowItemTypeEnum.FOODDRUG_CANCEL.getKey());
        List<String> disabilityList = Lists.newArrayList(FlowItemTypeEnum.DISABILITY_APPLY.getKey(), FlowItemTypeEnum.DISABILITY_CHANGE.getKey(), FlowItemTypeEnum.DISABILITY_REAPPLY.getKey(), FlowItemTypeEnum.DISABILITY_CANCEL.getKey());
        String itemStatus;
        //公司
        if (companyList.contains(flowInfoDO.getItemType())) {
            itemStatus = WebUtil.itemStatus(flowInfoDO.getItemStatus(), CompanyStatusEnum.class);
            flowInfoDO.setItemStatusText(itemStatus);
        }
        //个体
        if (merchantList.contains(flowInfoDO.getItemType())) {
            itemStatus = WebUtil.itemStatus(flowInfoDO.getItemStatus(), MerchantStatusEnum.class);
            flowInfoDO.setItemStatusText(itemStatus);
        }
        //食药
        if (fooddrugList.contains(flowInfoDO.getItemType())) {
            itemStatus = WebUtil.itemStatus(flowInfoDO.getItemStatus(), FooddrugStatusEnum.class);
            flowInfoDO.setItemStatusText(itemStatus);
        }
        //残联
        if (disabilityList.contains(flowInfoDO.getItemType())) {
            itemStatus = WebUtil.itemStatus(flowInfoDO.getItemStatus(), DisabilityStatusEnum.class);
            flowInfoDO.setItemStatusText(itemStatus);
        }
        return flowInfoDO;
    }
    /**
     * 返回当前状态
     * */
     private String itemStatusText(Integer state){
        switch (state){
            case 0:
                return "提交";
            case 1:
                return "审核中";
            case 2:
                return "审核通过";
            case 3:
                return "退回修改";
                default:
                    return "错误";
        }
     }
}
